$(function () {
    var layout = $("#wzjhgl_layout").layout();
    //======================
    //======设置查询条件========
    //======================
    //计划年份
    $("#wzjhgl_toolbar [name='jhnf']").numberspinner({
        min: 2000,
        max: 2100,
        editable: true
    });
    //计划月份
    $("#wzjhgl_toolbar [name='jhyf']").numberspinner({
        min: 1,
        max: 12,
        editable: true
    });
    //供应商
    $("#wzjhgl_toolbar [name='gys']").qyjgzcombobox();
    //搜索按钮
    $("#wzjhgl_toolbar [name='searchButton']").click(function () {
        reloadWzjhglGrid();
    });
    //======================
    //========操作按钮========
    //======================
    //物资计划新增按钮
    $("#wzjhgl_toolbar [name='xzwzjh']").click(function () {
        showWzjhglDialog("新增", $.webPath() + "/jhgl/wzjhgl/wzjhgl_content", $.webPath() + "/jhgl/wzjhgl/save_wzjh");
    });
    //物资计划修改按钮
    $("#wzjhgl_toolbar [name='xgwzjh']").click(function () {
        var row = $('#wzjhgl_grid').datagrid("getSelected");
        if (row)
            showWzjhglDialog("修改", $.webPath() + "/jhgl/wzjhgl/wzjhgl_content?id=" + row.id + "&type=" + row.clazz,
                $.webPath() + "/jhgl/wzjhgl/edit_wzjh?type=" + row.clazz);
        else
            $.messager.alert("提示", "请先选择物资计划!", "warning");
    });
    //物资计划删除按钮
    $("#wzjhgl_toolbar [name='scwzjh']").click(function () {
        var row = $('#wzjhgl_grid').datagrid("getSelected");
        if (row) {
            $.messager.confirm('确认', '是否确认删除此物资计划?', function (r) {
                if (r) {
                    wzjhAjax("/jhgl/wzjhgl/delete", {id: row.id, type: row.clazz});
                }
            });
        }
        else
            $.messager.alert("提示", "请先选择物资计划!", "warning")
    });
    //提交审核物资计划
    $("#wzjhgl_toolbar [name='tjshwzjh']").click(function () {
        var row = $('#wzjhgl_grid').datagrid("getSelected");
        if (row) {
            $.messager.confirm('确认', '是否确认提交此物资计划?', function (r) {
                if (r) {
                    wzjhAjax("/jhgl/wzjhgl/commit_wzjh", {id: row.id, type: row.clazz});
                }
            });
        }
        else
            $.messager.alert("提示", "请先选择物资计划!", "warning");
    });
    //======================
    //======物资计划列表========
    //======================
    //物资计划列表
    $('#wzjhgl_grid').datagrid({
        url: $.webPath() + '/jhgl/wzjhgl/wzjhList',
        toolbar: "#wzjhgl_toolbar",
        pagination: true,
        rownumbers: true,
        singleSelect: true,
        collapsible: true,
        pageNumber: 1,
        fit: true,
        fitColumns: true,
        queryParams: {
            type: 'Cgwzjh',
            jhnf: $("#wzjhgl_toolbar [name='jhnf']").val(),
            jhyf: $("#wzjhgl_toolbar [name='jhyf']").val()
        },
        columns: [
            [
                {field: 'jhbh', title: '计划编号', align: 'center', width: 143, formatter: wzjhCell},
                {field: 'gys_qc', title: '供应商', align: 'center', width: 184},
                {field: 'sbgs_jc', title: '申报公司', align: 'center', width: 124},
                {field: 'sbbm_qc', title: '申报部门', align: 'center', width: 124},
                {field: 'sbsl', title: '申报数量', align: 'right', width: 124,
                    formatter: function (value) {
                        var sl = formatSlForHtml(value, ",");
                        return sl;
                    }},
                {field: 'clazz', title: '计划类型', align: 'center', width: 74,
                    formatter: function (value) {
                        if (value == 'Zgwzjh')
                            return '自购';
                        if (value == 'Tpwzjh')
                            return '统配';
                    }},
                {field: 'zdr_xm', title: '制单人', align: 'center', width: 78},
                {field: 'zdsj', title: '制单时间', align: 'center', width: 183},
                {field: 'zt', title: '状态', align: 'center', width: 86,
                    formatter: formatWzjhglZT}
            ]
        ],
        onSelect: function (rowIndex, rowData) {
            if (rowData.zt == 'ybc') {
                $("#wzjhgl_toolbar [name='xzwzjh']").css('display', '');
                $("#wzjhgl_toolbar [name='xgwzjh']").css('display', '');
                $("#wzjhgl_toolbar [name='scwzjh']").css('display', '');
                $("#wzjhgl_toolbar [name='tjshwzjh']").css('display', '');
            } else {
                $("#wzjhgl_toolbar [name='xzwzjh']").css('display', '');
                $("#wzjhgl_toolbar [name='xgwzjh']").css('display', 'none');
                $("#wzjhgl_toolbar [name='scwzjh']").css('display', 'none');
                $("#wzjhgl_toolbar [name='tjshwzjh']").css('display', 'none');
            }
        },
        onLoadSuccess: function () {
            var rows = $('#wzjhgl_grid').datagrid("getRows");
            if (rows.length > 0) {
                $('#wzjhgl_grid').datagrid("selectRow", 0);
            }

            $(".datagrid-htable .datagrid-cell").css('text-align', 'center');
        },
        onDblClickCell: function (index, field) {
            if (field == "jhbh") {
                $("[name='xgwzjh']:visible").click();
            }
        }
    });


    //刷新表格
    function reloadWzjhglGrid() {
        $('#wzjhgl_grid').datagrid('reload', {
            type: $("#wzjhgl_toolbar [name='wzjhlb']").val(),
            jhbh: $("#wzjhgl_toolbar [name='jhbh']").val(),
            jhnf: $("#wzjhgl_toolbar [name='jhnf']").val(),
            jhyf: $("#wzjhgl_toolbar [name='jhyf']").val(),
            wzbm: $("#wzjhgl_toolbar [name='wzbm']").val(),
            gysId: $("#wzjhgl_toolbar [name='gys']").val(),
            zt: $("#wzjhgl_toolbar [name='zt']").val()
        });
        // $('#wzjhgl_layout').layout('panel', 'center').panel('refresh');
    }


    function wzjhAjax(url, data) {
        $.ajax({
            url: $.webPath() + url,
            dataType: 'json',
            type: 'POST',
            data: data,
            beforeSend: function () {
                $("#wzjhgl_layout").mask();
            },
            success: function (data) {
                $("#wzjhgl_layout").mask("hide");
                if (data.statusCode == 200) {
                    reloadWzjhglGrid();
                    $.messager.show({
                        title: '提示',
                        msg: data.message,
                        timeout: 3000,
                        showType: 'slide'
                    });
                } else {
                    $.messager.alert('提示', data.message, 'error');
                }
            },
            error: function () {

            }
        });
    }

    //物资计划弹出框
    function showWzjhglDialog(title, href, actionUrl) {
        var win = $.window({
            title: title,
            width: 700,
            height: 400,
            maximizable: true,
            //closed: true,
            iconCls: 'icon-add2',
            cache: false,
            url: href,
            modal: true,
            onMaximize: function () {
                $(this).find("#wzjhglForm").tabs("resize");
                $(this).find("#wzjhgl_wzjhmx_edatagrid").edatagrid("resize");

            },
            onRestore: function () {
                $(this).find("#wzjhglForm").tabs("resize");
                $(this).find("#wzjhgl_wzjhmx_edatagrid").edatagrid("resize");
            },
            buttons: [
                {
                    text: '保存',
                    handler: function () {
                        $(win).mask();
                        $('#wzjhglForm').form('submit', {
                            url: actionUrl,
                            onSubmit: function (param) {
                                //结束编辑列的编辑状态
                                $('#wzjhglForm #wzjhgl_wzjhmx_edatagrid').edatagrid("saveRow");
                                var r = $('#wzjhglForm #wzjhgl_wzjhmx_edatagrid').edatagrid("getSelected");
                                var index = $('#wzjhglForm #wzjhgl_wzjhmx_edatagrid').edatagrid("getRowIndex", r);
                                $('#wzjhglForm #wzjhgl_wzjhmx_edatagrid').edatagrid("endEdit", index);
                                //验证主信息表单
                                var isValid = $(this).form('validate');
                                if (!isValid) {
                                    $(win).mask('hide');
                                    $('#wzjhglForm').tabs('select', 0);
                                    return false;
                                }
                                //验证明细列表
                                var checkedRadio = $("#wzjhglForm [name='type']:checked").val();
                                if (checkedRadio == "Tpwzjh") {
                                    var tcgsid = $('#wzjhglForm :text[name="tpwzjh.tcgs.id"]').val();
                                    var tcbmid = $('#wzjhglForm :text[name="tpwzjh.tcbm.id"]').val();
                                    if (tcgsid == "" || tcbmid == "") {
                                        $(win).mask('hide');
                                        $.messager.alert("提示", "该供应商没有设置统筹公司和统筹部门，不能生成统配物资计划!", "waring");
                                        return false;
                                    }
                                }

                                var data = $('#wzjhglForm #wzjhgl_wzjhmx_edatagrid').edatagrid("getData");
                                if (!data.rows.length) {
                                    $(win).mask('hide');
                                    $.messager.alert("提示", "请填写物资计划明细!", "waring");
                                    $('#wzjhglForm').tabs('select', 1);
                                    return false;
                                }

                                for (var i = 0; i < data.rows.length; i++) {
                                    if (parseFloat(data.rows[i].sbsl) == 0) {
                                        $(win).mask('hide');
                                        $.messager.alert("提示", "请填写计划数量!", "waring");
                                        $('#wzjhglForm').tabs('select', 1);
                                        return false;
                                    }
                                }

                                var arrayPrefix = null;
                                var objectPrefix = null;

                                if (checkedRadio == "XyZgwzjh" || checkedRadio == "LjZgwzjh") {
                                    arrayPrefix = "zgwzjhmxList";
                                    objectPrefix = "zgwzjh";
                                }
                                if (checkedRadio == "Tpwzjh") {
                                    arrayPrefix = "tpwzjhmxList";
                                    objectPrefix = "tpwzjh";
                                }
                                var paramString = "{"
                                //物资计划明细
                                for (var i = 0; i < data.rows.length; i++) {
                                    var objectString = $.toJSONStringPrefix(data.rows[i], arrayPrefix + "[" + i + "].");
                                    paramString = paramString + objectString.substring(1, objectString.length - 1) + ",";
                                }
                                //物资计划明细总量
                                var footer = $('#wzjhglForm #wzjhgl_wzjhmx_edatagrid').datagrid('getFooterRows');
                                paramString = paramString + "\"" + objectPrefix + ".sbsl\":" + $(footer).get(0).sbsl;
                                paramString = paramString + "}";
                                $.extend(param, $.parseJSON(paramString));
                                return isValid;
                            },
                            success: function (data) {
                                $(win).mask('hide');
                                var json = $.parseJSON(data);
                                if (json.statusCode == 200) {
                                    $(win).dialog('close');
                                    reloadWzjhglGrid();
                                    $.messager.show({
                                        title: '提示',
                                        msg: json.message,
                                        timeout: 3000,
                                        showType: 'slide'
                                    });
                                } else {
                                    $.messager.alert('提示', json.message, 'error');
                                }
                            }
                        });
                    }
                }
            ]
        });
    }


})

function formatWzjhglZT(val, row) {
    if (val == 'ybc')
        val = '已保存';
    if (val == 'ytj')
        val = '已提交';
    if (val == 'ysp')
        val = '已审批';

    if (!row.processInstanceId) {
        return val;
    } else {
        return '<a href="javascript:viewWzjhglFlowPicture();" style="color: red">' + val + '</a>';
    }
}

function viewWzjhglFlowPicture() {
    var row = $('#wzjhgl_grid').datagrid("getSelected");
    $.window({
        title: "流程历史",
        iconCls: 'icon-add2',
        url: $.webPath() + "/flow/publish/flowPicture?processInstanceId=" + encodeURI(encodeURI(row.processInstanceId)) + "&businessNo=" + row.jhbh,
        width: 650,
        height: 500,
        closed: true,
        modal: true,
        isMax: true
    });
}